/**
 * 游戏activity
 */
package com.key;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.key.dialog.KeyExitDialog;
import com.key.dialog.KeyGiveupDialog;
import com.key.util.ChessMove;
import com.key.util.GameParams;
import com.key.util.KeyScore;
import com.key.util.UserSystemData;
import com.key.util.Util;

public class KeyChineseChessActivity extends Activity implements
		OnClickListener {
	/** Called when the activity is first created. */

	private ImageView giveChess;//让棋按钮
	private ImageView forgive;//悔棋按钮
	private ImageView giveup;//认输按钮
	private ImageView exit;//退出按钮
	private ImageView setting;//设置按钮
	private ImageView leftTitleView;//美女头像view

	private ImageButton gameStartButton;//游戏开始按钮
	// add by xiaosong.
	// private ImageButton OkButton = null;
	// private ImageButton ErrorButton = null;
	private PopupWindow popupWindow = null, invideWindow = null;//设置、让棋popwindow
	//让棋是否选择
	private boolean cannon = false, elephant = false, horse = false,
			official = false, soldier = false, vehicle = false;

	//是否已经让过棋
	private boolean isHasGiveChess = false;

	//初始让棋是否选择
	private void resetCheckBox() {
		soldier = false;
		cannon = false;
		elephant = false;
		horse = false;
		official = false;
		vehicle = false;
	}

	private TextView textScore = null;//分数

	public static ImageView imageAnimate;//移动Imageview
	public static ImageButton imgVRedLive;//红棋获胜显示
	public static ImageButton imgVBlackLive;//黑棋获胜显示
	public static ImageButton imgVAllLive;//和棋结果显示
	public static ImageButton imgKillKing;//将军显示

	public static KeyChineseChessView cv;//棋盘View

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//初始化所需Bitmap
		Bitmap imgPhoto = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.left_title0);		//美女头像
		Bitmap imgScore = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.scorepanel);		//分数
		Bitmap img = initLevelPanel(); //等级
		Bitmap imgGiveChess = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.givechess);//让棋
		Bitmap imgForgive = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.forgive);//悔棋
		Bitmap imgGiveUp = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.giveup);//认输
		Bitmap imgExit = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.exit);//退出
		Bitmap imgSetting = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.setting);//设置
		//
		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int DisplayWidth = dm.widthPixels;// 屏幕宽度
		int DisplayHeight = dm.heightPixels;// 屏幕高度
		KeyChineseChessView.screenHeight = DisplayHeight;
		KeyChineseChessView.screenWidth = DisplayWidth;
		setContentView(R.layout.main);
		
		//初始化等级panel显示
		ImageView imgView = (ImageView) findViewById(R.id.levelpanel);
		int photoWidth = imgPhoto.getWidth();//美女头像宽度
		int scoreWidth = imgScore.getWidth();//分数宽度
		int imgW = img.getWidth();//等级宽度
		int imgH = img.getHeight();//等级高度
		
		//游戏等级panel压缩比例
		int layout_w = DisplayWidth - photoWidth - scoreWidth;
		Matrix matrix = new Matrix();
		matrix.postScale((((float) layout_w / imgW) + (float) 0.009), 1);
		//重置等级Bitmap
		Bitmap resizebmp = Bitmap.createBitmap(img, 0, 0, imgW, imgH, matrix,
				true);
		imgView.setImageBitmap(resizebmp);
		//根据屏幕大小，初始化下排按钮显示大小
		float buttonMatrix = 1;//压缩比例
		float nowChessBoardHeight = 662 * ((float) DisplayHeight / 800);
		if (((float) (DisplayHeight - nowChessBoardHeight) / imgGiveChess
				.getHeight()) >= ((float) (DisplayWidth - 85) / (5 * imgGiveChess
				.getWidth()))) {
			buttonMatrix = ((float) (DisplayWidth - 85) / (5 * imgGiveChess
					.getWidth()));
		} else {
			buttonMatrix = ((float) (DisplayHeight - nowChessBoardHeight) / imgGiveChess
					.getHeight());
		}
		//获胜、输棋、和棋、将军显示imageview控件
		imageAnimate = (ImageView) findViewById(R.id.moveImage);
		imageAnimate.setVisibility(View.GONE);
		imgVRedLive = (ImageButton) findViewById(R.id.redLive);
		imgVRedLive.setVisibility(View.GONE);
		imgVBlackLive = (ImageButton) findViewById(R.id.blackLive);
		imgVBlackLive.setVisibility(View.GONE);
		imgVAllLive = (ImageButton) findViewById(R.id.allLive);
		imgVAllLive.setVisibility(View.GONE);
		imgKillKing = (ImageButton) findViewById(R.id.killKing);
		imgKillKing.setVisibility(View.GONE);

		//头像ImageView
		leftTitleView = (ImageView) findViewById(R.id.leftTitle);

		//下排按钮ImageView控件
		giveChess = (ImageView) findViewById(R.id.givechess);
		forgive = (ImageView) findViewById(R.id.forgive);
		giveup = (ImageView) findViewById(R.id.giveup);
		exit = (ImageView) findViewById(R.id.exit);
		setting = (ImageView) findViewById(R.id.setting);

		//根据下排按钮压缩比例调整按钮显示
		matrix = new Matrix();
		matrix.postScale(buttonMatrix, buttonMatrix);
		Bitmap resizeGiveChessBmp = Bitmap
				.createBitmap(imgGiveChess, 0, 0, imgGiveChess.getWidth(),
						imgGiveChess.getHeight(), matrix, true);
		giveChess.setImageBitmap(resizeGiveChessBmp);

		matrix = new Matrix();
		matrix.postScale(buttonMatrix, buttonMatrix);
		Bitmap resizeForgiveBmp = Bitmap.createBitmap(imgForgive, 0, 0,
				imgForgive.getWidth(), imgForgive.getHeight(), matrix, true);
		forgive.setImageBitmap(resizeForgiveBmp);

		matrix = new Matrix();
		matrix.postScale(buttonMatrix, buttonMatrix);
		Bitmap resizeGiveUpBmp = Bitmap.createBitmap(imgGiveUp, 0, 0,
				imgGiveUp.getWidth(), imgGiveUp.getHeight(), matrix, true);
		giveup.setImageBitmap(resizeGiveUpBmp);

		matrix = new Matrix();
		matrix.postScale(buttonMatrix, buttonMatrix);
		Bitmap resizeExitBmp = Bitmap.createBitmap(imgExit, 0, 0,
				imgExit.getWidth(), imgExit.getHeight(), matrix, true);
		exit.setImageBitmap(resizeExitBmp);

		matrix = new Matrix();
		matrix.postScale(buttonMatrix, buttonMatrix);
		Bitmap resizeSettingBmp = Bitmap.createBitmap(imgSetting, 0, 0,
				imgSetting.getWidth(), imgSetting.getHeight(), matrix, true);
		setting.setImageBitmap(resizeSettingBmp);

		initLeftTitle();//初始化头像
		initLevelPanel();//初始化等级panel
		initView();//初始化棋盘界面
		initContants();//初始化游戏静态变量
		GameParams.activity = this;//游戏参数
	}

	/**
	 * 初始化棋盘界面
	 */
	public void initView() {
		gameStartButton = (ImageButton) findViewById(R.id.gameStart);
		gameStartButton.setOnClickListener(this);
		gameStartButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.game_start_down));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.game_start_up));
				}
				return false;
			}
		});

		initButton();
		initScore();
		setScore();
	}

	/**
	 * 初始化用户分数显示
	 */
	private void initScore() {
		textScore = (TextView) findViewById(R.id.score);
	}

	/**
	 * 设置用户分数显示
	 */
	private void setScore() {
		textScore.setText(Integer.toString(UserSystemData.UserInfo
				.getUserGrade()));
	}

	/**
	 * 初始化下排按钮
	 */
	private void initButton() {
		initGivechessButton();
		initForgiveButton();
		initGiveupButton();
		initExitButton();
		initSettingButton();
	}

	/**
	 * 初始化让棋按钮
	 */
	private void initGivechessButton() {
		giveChess.setOnClickListener(this);
		giveChess.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageView) v).setBackgroundColor(Color.WHITE);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageView) v).setBackgroundColor(Color.TRANSPARENT);
				}
				return false;
			}
		});
	}

	/**
	 * 初始化悔棋按钮
	 */
	private void initForgiveButton() {
		forgive.setOnClickListener(this);
		forgive.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageView) v).setBackgroundColor(Color.WHITE);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageView) v).setBackgroundColor(Color.TRANSPARENT);
				}
				return false;
			}
		});
	}

	/**
	 * 初始化让棋按钮
	 */
	private void initGiveupButton() {
		giveup.setOnClickListener(this);
		giveup.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageView) v).setBackgroundColor(Color.WHITE);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageView) v).setBackgroundColor(Color.TRANSPARENT);
				}
				return false;
			}
		});
	}

	/**
	 * 初始化退出按钮
	 */
	private void initExitButton() {
		exit.setOnClickListener(this);
		exit.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageView) v).setBackgroundColor(Color.WHITE);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageView) v).setBackgroundColor(Color.TRANSPARENT);
				}
				return false;
			}
		});
	}

	/**
	 * 初始化设置按钮
	 */
	private void initSettingButton() {
		setting.setOnClickListener(this);
		setting.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageView) v).setBackgroundColor(Color.WHITE);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageView) v).setBackgroundColor(Color.TRANSPARENT);
				}
				return false;
			}
		});
	}

	/**
	 * 创建设置对话框
	 * @param v
	 */
	private void createSettingDialog(View v) {
		initSettingDialog();
		createDialogSetting(v);
	}

	/**
	 * 创建让棋对话框
	 * @param v
	 */
	private void createInvideDialog(View v) {
		initInviteDialog();
		createInviteDialog(v);
	}

	/**
	 * 显示游戏设置对话框
	 * @param v
	 */
	private void createDialogSetting(View v) {
		popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
	}

	/**
	 * 显示让棋对话框
	 * @param v
	 */
	private void createInviteDialog(View v) {
		invideWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
	}

	/**
	 * 初始化让棋对话框
	 */
	private void initInviteDialog() {

		ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(
				R.layout.key_invitechess_menu, null);
		if (invideWindow == null) {
			invideWindow = new PopupWindow(vg, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
		}
		if (invideWindow.isShowing()) {
			invideWindow.dismiss();
		}

		CheckBox checkboxsoldier = (CheckBox) vg
				.findViewById(R.id.checkbox_soldier);
		checkboxsoldier
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							soldier = true;
						} else {
							soldier = false;
						}
					}
				});
		CheckBox checkboxhorse = (CheckBox) vg
				.findViewById(R.id.checkbox_horse);
		checkboxhorse
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							horse = true;
						} else {
							horse = false;
						}
					}
				});
		CheckBox checkboxelephant = (CheckBox) vg
				.findViewById(R.id.checkbox_elephant);
		checkboxelephant
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							elephant = true;
						} else {
							elephant = false;
						}
					}
				});
		CheckBox checkboxcannon = (CheckBox) vg
				.findViewById(R.id.checkbox_cannon);
		checkboxcannon
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							cannon = true;
						} else {
							cannon = false;
						}
					}
				});
		CheckBox checkboxofficial = (CheckBox) vg
				.findViewById(R.id.checkbox_official);
		checkboxofficial
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							official = true;
						} else {
							official = false;
						}
					}
				});
		CheckBox checkboxvehicle = (CheckBox) vg
				.findViewById(R.id.checkbox_vehicle);
		checkboxvehicle
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							vehicle = true;
						} else {
							vehicle = false;
						}
					}
				});

		ImageButton OkButton = (ImageButton) vg.findViewById(R.id.button_ok);
		OkButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (GameParams.isGameStart == false) {
					if (isHasGiveChess == false) {
						caculateGiveChess();
						isHasGiveChess = true;
					}
					if (invideWindow.isShowing()) {
						invideWindow.dismiss();
							Message msg = new Message();
							msg.what = 0;
							handler.sendMessage(msg);
					}
				}
			}
		});
		OkButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.sure_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.sure_up_btn));
				}
				return false;
			}
		});

		ImageButton ErrorButton = (ImageButton) vg
				.findViewById(R.id.button_error);
		ErrorButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				resetCheckBox();
				if (invideWindow.isShowing()) {
					invideWindow.dismiss();
				}
			}
		});
		ErrorButton.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.cancel_down_btn));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.cancel_up_btn));
				}
				return false;
			}
		});
	}

	/**
	 * 初始化设置对话框
	 */
	private void initSettingDialog() {

		ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(
				R.layout.key_popwindow_menu, null);
		if (popupWindow == null) {
			popupWindow = new PopupWindow(vg, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
		}
		if (popupWindow.isShowing()) {
			popupWindow.dismiss();
		}

		CheckBox music = (CheckBox) vg.findViewById(R.id.checkbox_music_degree);
		CheckBox single = (CheckBox) vg
				.findViewById(R.id.checkbox_single_degree);
		SeekBar musicBar = (SeekBar) vg.findViewById(R.id.seekbar_Music);
		SeekBar singleBar = (SeekBar) vg.findViewById(R.id.seekbar_Single);

		musicBar.setProgress(UserSystemData.keyMusic.getMusicDegree());
		singleBar.setProgress(UserSystemData.keyMusic.getSingleDegree());
		if (UserSystemData.keyMusic.getMusicChecked() == true) {
			music.setChecked(true);
		} else {
			music.setChecked(false);
		}
		if (UserSystemData.keyMusic.getSingleChecked() == true) {
			single.setChecked(true);
		} else {
			single.setChecked(false);
		}

		music.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					UserSystemData.keyMusic.setMusicChecked(true);
					GameParams.chessAudio.setMusicMute(true);
				} else {
					UserSystemData.keyMusic.setMusicChecked(false);
					GameParams.chessAudio.setMusicMute(false);
				}
			}
		});
		single.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					UserSystemData.keyMusic.setSingleChecked(true);
				} else {
					UserSystemData.keyMusic.setSingleChecked(false);
				}
			}
		});
		musicBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStartTrackingTouch(SeekBar musicBar) {
				// TODO Auto-generated method stub
			}

			public void onProgressChanged(SeekBar musicBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				int i = musicBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setMusicDegree(i);
					GameParams.chessAudio.adjustVolume();
				}
				if (i > 9) {
					musicBar.setProgress(9);
				} else if (i < 1) {
					musicBar.setProgress(1);
				}
			}

			public void onStopTrackingTouch(SeekBar musicBar) {
				// TODO Auto-generated method stub
				int i = musicBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setMusicDegree(i);
					GameParams.chessAudio.adjustVolume();
				}
			}
		});
		singleBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStartTrackingTouch(SeekBar singleBar) {
				// TODO Auto-generated method stub
			}

			public void onProgressChanged(SeekBar singleBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				int i = singleBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setSingleDegree(i);
				}
				if (i > 9) {
					singleBar.setProgress(9);
				} else if (i < 1) {
					singleBar.setProgress(1);
				}
			}

			public void onStopTrackingTouch(SeekBar singleBar) {
				// TODO Auto-generated method stub
				int i = singleBar.getProgress();
				if (i >= 0) {
					UserSystemData.keyMusic.setSingleDegree(i);
				}
			}
		});

	}

	//屏蔽返回键
	@Override
	public boolean onKeyDown(int kCode, KeyEvent kEvent) {

		if (kCode == KeyEvent.KEYCODE_BACK) {
			if (popupWindow != null) {
				if (popupWindow.isShowing()) {
					popupWindow.dismiss();
					return false;
				}
			} else if (invideWindow != null) {
				if (invideWindow.isShowing()) {
					invideWindow.dismiss();
					return false;
				}
			}
			return true;
		}
		return super.onKeyDown(kCode, kEvent);
	}

	//下排按钮点击
	public void onClick(View v) {
		switch (v.getId()) {
		//开始游戏
		case R.id.gameStart:
			GameParams.isGameStart = true;
			setScore();
			GameParams.chessAudio.playRaw(GameParams.soundNewGame);
			gameStartButton.setVisibility(View.GONE);
			break;
		//悔棋
		case R.id.forgive:
			if (KeyChineseChessView.isThinking) {
				Util.toastPopWindow(this, "程序在思考中");
			} else {
				if (GameParams.isGameStart) {
					if (KeyChineseChessView.moveStack.size() > 1) {
						if (caculateInvideChess() == true) {
							setScore();
							ChessMove move = KeyChineseChessView.moveStack
									.pop();
							KeyChineseChessView.position[move.from.x][move.from.y] = move.chessFrom;
							KeyChineseChessView.position[move.to.x][move.to.y] = move.chessTo;
							move = KeyChineseChessView.moveStack.pop();
							KeyChineseChessView.position[move.from.x][move.from.y] = move.chessFrom;
							KeyChineseChessView.position[move.to.x][move.to.y] = move.chessTo;
							KeyChineseChessView.rsel = false;
							KeyChineseChessView.bsel = false;
							cv.refreshRuleListPosition();
							cv.invalidate();
						}
					}
				}
			}
			break;
		//游戏设置
		case R.id.setting:
			createSettingDialog(v);
			Util.resultWrite();
			break;
		//认输
		case R.id.giveup:
			if (KeyChineseChessView.isThinking) {
				Util.toastPopWindow(this, "程序在思考中");
			} else {
				if (GameParams.isGameStart) {
					Dialog giveupDialog = new KeyGiveupDialog(this,
							R.style.dialogGiveup);
					giveupDialog.show();
				} else {
					Util.toastPopWindow(this, "游戏未开始");
				}
			}
			break;
		//让棋
		case R.id.givechess:
			if (KeyChineseChessView.isThinking) {
				Util.toastPopWindow(this, "程序在思考中");
			} else {
				if (GameParams.isGameStart == false) {
					createInvideDialog(v);
				} else {
					Util.toastPopWindow(this, "游戏已开始");
				}
			}
			break;
		//退出
		case R.id.exit:
			if (KeyChineseChessView.isThinking) {
				Util.toastPopWindow(this, "程序在思考中");
			} else {
				if (GameParams.isGameStart == false) {
					Dialog exitDialog = new KeyExitDialog(this, R.style.dialog);
					exitDialog.show();
				} else {
					Util.toastPopWindow(this, "游戏已开始");
				}
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 退出前销毁popwindow
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (popupWindow != null) {
			popupWindow.dismiss();
		}
		if (invideWindow != null) {
			invideWindow.dismiss();
		}
		super.onPause();
	}

	/**
	 * 计算认输
	 */
	public void caculateGiveupChess() {
		if (UserSystemData.UserInfo.inviteChess(KeyScore.subScoreIfGiveup) >= 0) {
			if (UserSystemData.UserInfo.write() == true) {
				;
			} else {
				Util.toastPopWindow(this, "放弃失败");
			}
		} else {
			UserSystemData.UserInfo.getUserInfo().setUserGrade(0);
		}
	}

	/**
	 * 计算悔棋
	 * @return
	 */
	private boolean caculateInvideChess() {
		if (UserSystemData.UserInfo.inviteChess(KeyScore.subScoreIfForgive) >= 0) {
			if (UserSystemData.UserInfo.write() == true) {
				return true;
			} else {
				Util.toastPopWindow(this, "悔棋失败");
			}
		} else {
			Util.toastPopWindow(this, "分数不够");
		}
		return false;
	}

	/**
	 * 计算让棋
	 */
	private void caculateGiveChess() {
		int iValue = 0;
		if (soldier == true) {
			iValue += 1;
		}
		if (official == true) {
			iValue += 2;
		}
		if (elephant == true) {
			iValue += 3;
		}
		if (horse == true) {
			iValue += 4;
		}
		if (cannon == true) {
			iValue += 5;
		}
		if (vehicle == true) {
			iValue += 6;
		}
		if (UserSystemData.UserInfo.inviteChess(iValue) >= 0) {
			if (UserSystemData.UserInfo.write() == true) {
				if (soldier == true) {
					KeyChineseChessView.position[3][2] = KeyChineseChessView.NOCHESS;
				}
				if (official == true) {
					KeyChineseChessView.position[0][3] = KeyChineseChessView.NOCHESS;
				}
				if (elephant == true) {
					KeyChineseChessView.position[0][2] = KeyChineseChessView.NOCHESS;
				}
				if (horse == true) {
					KeyChineseChessView.position[0][1] = KeyChineseChessView.NOCHESS;
				}
				if (cannon == true) {
					KeyChineseChessView.position[2][1] = KeyChineseChessView.NOCHESS;
				}
				if (vehicle == true) {
					KeyChineseChessView.position[0][0] = KeyChineseChessView.NOCHESS;
				}
			} else {
				Util.toastPopWindow(this, "让棋失败");
			}
		} else {
			Util.toastPopWindow(this, "分数不够");
		}
	}

	/**
	 * 棋子移动动画
	 * 
	 * @param frameBitmap 移动Bitmap
	 */
	public static void runFrame(Bitmap frameBitmap, float fromX, float toX,
			float fromY, float toY) {
		// 初始化移动画面
		imageAnimate.setVisibility(View.VISIBLE);
		imageAnimate.setImageBitmap(frameBitmap);
		imageAnimate.setAlpha(125);
		//移动动画
		TranslateAnimation anim = new TranslateAnimation(fromX, toX, fromY, toY);
		anim.setAnimationListener(new AnimationListener() {
			public void onAnimationStart(Animation arg0) {
				// TODO Auto-generated method stub
			}

			public void onAnimationRepeat(Animation arg0) {
				// TODO Auto-generated method stub
			}

			public void onAnimationEnd(Animation arg0) {
				// TODO Auto-generated method stub
				imageAnimate.setVisibility(View.GONE);
			}
		});
		anim.setDuration(500);
		imageAnimate.setAnimation(anim);
		anim.startNow();
	}

	/**
	 * 初始化头像显示
	 */
	public void initLeftTitle() {
		switch (GameParams.gameLevel) {
		case 1:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title0));
			break;
		case 2:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title1));
			break;
		case 3:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title2));
			break;
		case 4:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title3));
			break;
		case 5:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title4));
			break;
		case 6:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title5));
			break;
		case 7:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title6));
			break;
		case 8:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title7));
			break;
		case 9:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title8));
			break;
		case 10:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title9));
			break;
		default:
			leftTitleView.setImageDrawable(getResources().getDrawable(
					R.drawable.left_title0));
			break;
		}
	}

	/**
	 * 初始化等级显示
	 */
	public Bitmap initLevelPanel() {
		Bitmap returnBitmap;
		switch (GameParams.gameLevel) {
		case 1:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel1);
			break;
		case 2:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel2);
			break;
		case 3:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel3);
			break;
		case 4:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel4);
			break;
		case 5:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel5);
			break;
		case 6:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel6);
			break;
		case 7:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel7);
			break;
		case 8:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel8);
			break;
		case 9:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel9);
			break;
		case 10:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel10);
			break;
		default:
			returnBitmap = BitmapFactory.decodeResource(this.getResources(),
					R.drawable.levelpanel1);
			break;
		}
		return returnBitmap;
	}

	/**
	 * 初始化常量
	 */
	public void initContants() {
		KeyChineseChessView.rsel = false;
		KeyChineseChessView.bsel = false;
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 9; j++) {
				KeyChineseChessView.position[i][j] = KeyChineseChessView.NOCHESS;
			}
		}
		GameParams.isGameStart = false;
		KeyChineseChessView.isThinking = false;
		KeyChineseChessView.position[0][0] = KeyChineseChessView.B_CAR;
		KeyChineseChessView.position[0][1] = KeyChineseChessView.B_HORSE;
		KeyChineseChessView.position[0][2] = KeyChineseChessView.B_ELEPHANT;
		KeyChineseChessView.position[0][3] = KeyChineseChessView.B_BISHOP;
		KeyChineseChessView.position[0][4] = KeyChineseChessView.B_KING;
		KeyChineseChessView.position[0][5] = KeyChineseChessView.B_BISHOP;
		KeyChineseChessView.position[0][6] = KeyChineseChessView.B_ELEPHANT;
		KeyChineseChessView.position[0][7] = KeyChineseChessView.B_HORSE;
		KeyChineseChessView.position[0][8] = KeyChineseChessView.B_CAR;

		KeyChineseChessView.position[2][1] = KeyChineseChessView.B_CANON;
		KeyChineseChessView.position[2][7] = KeyChineseChessView.B_CANON;

		KeyChineseChessView.position[3][0] = KeyChineseChessView.B_PAWN;
		KeyChineseChessView.position[3][2] = KeyChineseChessView.B_PAWN;
		KeyChineseChessView.position[3][4] = KeyChineseChessView.B_PAWN;
		KeyChineseChessView.position[3][6] = KeyChineseChessView.B_PAWN;
		KeyChineseChessView.position[3][8] = KeyChineseChessView.B_PAWN;

		KeyChineseChessView.position[9][0] = KeyChineseChessView.R_CAR;
		KeyChineseChessView.position[9][1] = KeyChineseChessView.R_HORSE;
		KeyChineseChessView.position[9][2] = KeyChineseChessView.R_ELEPHANT;
		KeyChineseChessView.position[9][3] = KeyChineseChessView.R_BISHOP;
		KeyChineseChessView.position[9][4] = KeyChineseChessView.R_KING;
		KeyChineseChessView.position[9][5] = KeyChineseChessView.R_BISHOP;
		KeyChineseChessView.position[9][6] = KeyChineseChessView.R_ELEPHANT;
		KeyChineseChessView.position[9][7] = KeyChineseChessView.R_HORSE;
		KeyChineseChessView.position[9][8] = KeyChineseChessView.R_CAR;

		KeyChineseChessView.position[7][1] = KeyChineseChessView.R_CANON;
		KeyChineseChessView.position[7][7] = KeyChineseChessView.R_CANON;

		KeyChineseChessView.position[6][0] = KeyChineseChessView.R_PAWN;
		KeyChineseChessView.position[6][2] = KeyChineseChessView.R_PAWN;
		KeyChineseChessView.position[6][4] = KeyChineseChessView.R_PAWN;
		KeyChineseChessView.position[6][6] = KeyChineseChessView.R_PAWN;
		KeyChineseChessView.position[6][8] = KeyChineseChessView.R_PAWN;
		KeyChineseChessView.moveStack.clear();
	}

	/**
	 * handler操作
	 */
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				cv.invalidate();
				setScore();
				break;
			default:
				break;
			}
		}
	};
}
